package myservice.android.activities;

import java.util.ArrayList;
import java.util.Calendar;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.PopupMenu;
import myservice.android.utilities.Record;
import myservice.android.utilities.RecordAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class CallListActivity extends BaseActivity {
	
	private Button addCallButton;
	private ArrayList<Record> callData;
	private Spinner sortCallsSpinner;
	private ListView callList;
	private TextView noCallsDefinedText;
	private RecordAdapter callAdapter;
	
	private long personId = 0;
	
	@Override
	protected void initializeLayoutIdAndTitle() {
		
		layoutId = R.layout.call_list;
		
	}

	@Override
	protected void retrieveViews() {
		
        addCallButton = (Button) findViewById(R.id.addCallButton);    
        sortCallsSpinner = (Spinner) findViewById(R.id.sort_spinner);
        callList = (ListView) findViewById(R.id.callsList);
        noCallsDefinedText = (TextView) findViewById(R.id.noCallsMessage);
		
	}

	@Override
	protected void loadActivityParameters() {

		personId = activityParameters.getLong("person_id");
		
	}

	@Override
	protected void assignListeners() {   	
        
        addCallButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {				
				
				final Dialog dialog = new Dialog(CallListActivity.this);
				dialog.setContentView(R.layout.add_call_biblestudy_person_dialog);				
				dialog.setTitle(Global.res.getString(R.string.title_add_new_call));
				
				Button saveButton = (Button) dialog.findViewById(R.id.saveButton);				
				Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
				TextView personLabel = (TextView) dialog.findViewById(R.id.personLabel);
				final Spinner personList = (Spinner) dialog.findViewById(R.id.personSpinner);				

				Cursor c = Database.select("SELECT personid,name FROM persons WHERE timestamp<>"+Global.TIMESTAMP_DELETED+" AND status<>0 ORDER BY name");
				if (c.getCount()==0) {
					c.close();
					Global.displayToast(CallListActivity.this, Global.res.getString(R.string.message_no_interested_defined));
					return;
				}
				String[] personNames = new String[c.getCount()];
				final long[] personIds = new long[c.getCount()];				
				int i=0;
				while (c.moveToNext()) {
					personNames[i]=c.getString(c.getColumnIndex("name"));
					personIds[i]=c.getLong(c.getColumnIndex("personid"));
					i++;						
				}				
				c.close();	
				
				ArrayAdapter<String> adapter=new ArrayAdapter<String>(CallListActivity.this,android.R.layout.simple_spinner_item,personNames);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				personList.setAdapter(adapter);							
					
				if (personId != 0) {
					personLabel.setVisibility(View.GONE);
					personList.setVisibility(View.GONE);
				}
				
				final CheckBox bibleStudyCheckbox = (CheckBox) dialog.findViewById(R.id.bibleStudyConductedCheckbox);
				final EditText commentsField = (EditText) dialog.findViewById(R.id.commentsField);
				
				saveButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {	
												
						long pid;
						if (personId !=0)
							pid = personId;
						else
							pid = personIds[personList.getSelectedItemPosition()];						
						
						Calendar today = Calendar.getInstance();
						
						int bibleStudy = 0;
						if (bibleStudyCheckbox.isChecked())
							bibleStudy = 1;						
						
						Database.execSQL("INSERT INTO calls (callid,date,month,year,personid,territoryid,comments,biblestudy,timestamp) VALUES ("+Database.getUniqueRowId("calls")+
								         ","+today.get(Calendar.DATE)+","+today.get(Calendar.MONTH)+","+today.get(Calendar.YEAR)+","+pid+
								         ",0,'"+Global.fixText(commentsField.getText())+"',"+bibleStudy+","+Global.getTimeStamp()+")");	
						
						// Increment return calls if this option is enabled
						if (Global.autoIncrementReturnCalls==true) {
							Cursor c = Database.select("SELECT COUNT(*) AS c FROM ministry WHERE date="+today.get(Calendar.DATE)+" AND month="+today.get(Calendar.MONTH)+
									                   " AND year="+today.get(Calendar.YEAR));
							c.moveToNext();
							if (c.getInt(c.getColumnIndex("c"))==0) { // Create a new entry in database if no data exists for today
								Database.execSQL("INSERT INTO ministry (date,month,year,hours,minutes,chours,cminutes,magazines,brochures,books,returncalls,comments,timestamp)"+
							                     " VALUES ("+today.get(Calendar.DATE)+","+today.get(Calendar.MONTH)+","+today.get(Calendar.YEAR)+",0,0,0,0,0,0,0,0,'',"+Global.getTimeStamp()+")");
							}							
							c.close();
							// Increment return calls by one
							Database.execSQL("UPDATE ministry SET returncalls=returncalls+1, timestamp="+Global.getTimeStamp()+" WHERE date="+today.get(Calendar.DATE)+
									         " AND month="+today.get(Calendar.MONTH)+" AND year="+today.get(Calendar.YEAR));
							Global.displayToast(CallListActivity.this, Global.res.getString(R.string.message_return_calls_incremented));
						}
						
						dialog.dismiss();
						updateList();
					}			
				});
				
				cancelButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();				
					}			
				});		
				
				dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);								
				dialog.show();					
															
			}
        });       
                
        sortCallsSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long id) {
				updateList();				
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
        	
        });
		
	}		                    
    
	private void updateList() {		
		
		PopupMenu.createPopupMenu(this);
		PopupMenu.menuSection3.setVisibility(View.GONE);
		PopupMenu.menuSection4.setVisibility(View.GONE);
		
		callData = new ArrayList<Record>();
		
		// Get the 100 most recent calls only for performance reasons
		String sql = "SELECT callid,year,month,date,call_personid,biblestudy,name,call_comments FROM (SELECT callid,year,month,date,calls.personid AS call_personid,"+
		             "name,biblestudy,calls.comments AS call_comments FROM calls LEFT JOIN persons ON calls.personid=persons.personid WHERE calls.timestamp<>"+Global.TIMESTAMP_DELETED;
		if (personId!=0) // Displaying calls only for a specific person
			sql = sql + " AND calls.personid="+personId;
		else {			
			// Do not include calls to inactive persons unless the "Display inactive persons" check box is selected
			if (!Global.showInactives)
				sql = sql + " AND (calls.personid=0 OR territoryid<>0 OR (calls.personid<>0 AND status>0))";		    
		}
		
		sql = sql + " ORDER BY year DESC,month DESC,date DESC LIMIT 100)";
		if (sortCallsSpinner.getSelectedItemPosition()==1)
			sql=sql+" ORDER BY year,month,date";
		else
			sql=sql+" ORDER BY year DESC,month DESC,date DESC";
		
    	Cursor cursor = Database.select(sql);    		
    	
    	boolean noCallsDefined = true;

    	while (cursor.moveToNext()) {    		
    		
    		noCallsDefined=false;
    		Record rec = new Record();
    		rec.id=cursor.getInt(cursor.getColumnIndex("callid"));
    		String date = Global.getFormattedDate(cursor.getInt(cursor.getColumnIndex("year")), cursor.getInt(cursor.getColumnIndex("month")), cursor.getInt(cursor.getColumnIndex("date")));
    		if (personId!=0) {
    			rec.firstLine=date;
    		} else {
    			if (cursor.getLong(cursor.getColumnIndex("call_personid"))!=0) {
    				rec.firstLine = cursor.getString(cursor.getColumnIndex("name"))+" ("+date+")";
    			} else
    				rec.firstLine=date;
    		}
    		rec.secondLine=cursor.getString(cursor.getColumnIndex("call_comments"));
    		rec.status=cursor.getInt(cursor.getColumnIndex("biblestudy"));    		
    		callData.add(rec);
    	}	
    	cursor.close();    	 
    	
    	if (noCallsDefined==true) {
    		noCallsDefinedText.setVisibility(View.VISIBLE);
    	}
    	else {
    		noCallsDefinedText.setVisibility(View.GONE);
    	}
    	
        callAdapter = new RecordAdapter(this, R.layout.list_row, callData, 1);
        callList.setAdapter(callAdapter);
        
        callList.setOnItemLongClickListener(new OnItemLongClickListener () {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				final long cid = callData.get(position).id;
				
				PopupMenu.menuHeading.setText(callData.get(position).firstLine);
				
				PopupMenu.menuOption1.setText(Global.res.getString(R.string.menuitem_modify_call));		
				PopupMenu.menuOption2.setText(Global.res.getString(R.string.menuitem_delete_call));						
				
				PopupMenu.menuOption1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						clickCall(cid);				
					}					
				});
				
				PopupMenu.menuOption2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(CallListActivity.this);
						alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
						alertDialogBuilder
							.setMessage(Global.res.getText(R.string.message_delete_call_confirmation))
							.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									
									// Reduce the number of return calls if this option is enabled
									if (Global.autoIncrementReturnCalls==true) {
										Cursor c1 = Database.select("SELECT date,month,year FROM calls WHERE callid="+cid);
										c1.moveToNext();
										int date = c1.getInt(c1.getColumnIndex("date"));
										int month = c1.getInt(c1.getColumnIndex("month"));
										int year = c1.getInt(c1.getColumnIndex("year"));
										Cursor c2 = Database.select("SELECT returncalls FROM ministry WHERE date="+date+" AND month="+month+" AND year="+year);
										if (c2.moveToNext()) {
											if (c2.getInt(c2.getColumnIndex("returncalls"))>0) {
												Database.execSQL("UPDATE ministry SET returncalls=returncalls-1, timestamp="+Global.getTimeStamp()+" WHERE date="+date+
														         " AND month="+month+" AND year="+year);
												Global.displayToast(CallListActivity.this, Global.res.getString(R.string.message_return_calls_reduced));
											}
										}
										c2.close();
										c1.close();
									}
									
									Database.deleteCall(cid);
									updateList();
								}
							  })
							.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});
				 
						AlertDialog alertDialog = alertDialogBuilder.create();
						alertDialog.show();					
					}					
				});										
				
				PopupMenu.showMenu(view);				
				
				return true;
			}
        	
        });        
        
        
        callList.setOnItemClickListener(new OnItemClickListener() {
        	
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				 
				clickCall(callData.get(position).id);
			     				
			}			
        	
        });
    	
	}  
	
	private void clickCall(long cid) {
		 Intent i = new Intent(getApplicationContext(),CallActivity.class);
	     i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
	     i.putExtra("call_id",cid);			     
	     startActivity(i);		
	}	
	
	@Override
	protected void updateUi() {
		
		String title = Global.res.getString(R.string.title_calls);
		
		if (personId!=0) {
			
			Cursor cursor = Database.select("SELECT name FROM persons WHERE personid="+personId);
			cursor.moveToNext();
			title = title + " ("+cursor.getString(cursor.getColumnIndex("name"))+")";
			cursor.close();
			
		}
    	
    	activityTitleView.setText(title);
    	
    	updateList();
		
	}	

}
